package com.hu.network.http.interceptor;

import android.support.annotation.NonNull;

import java.io.IOException;

import com.hu.network.http.bodyImpl.ResponseBodyImpl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/28
 */
public class ResponseInterceptor implements Interceptor {
    private ResponseBodyImpl.ProgressListener progressListener = new ResponseBodyImpl.ProgressListener() {
        @Override
        public void progress(long bytesRead, long contentLength, boolean done) {
            System.out.println(bytesRead);
            System.out.println(contentLength);
            System.out.println(done);
            System.out.format("%d%% done%n", 100L * bytesRead / contentLength);
        }
    };
    private String tag;

    public ResponseInterceptor(ResponseBodyImpl.ProgressListener progressListener) {
        if (progressListener != null) {
            this.progressListener = progressListener;
        }
    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Response originalResponse = chain.proceed(chain.request());
        if (request.tag().equals(this.tag)) {
            return originalResponse.newBuilder().body(new ResponseBodyImpl(originalResponse.body(), this.progressListener)).build();
        } else {
            return originalResponse;
        }
    }

    public void setTag(String tag) {
        this.tag = tag;
    }
}
